<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Model extends CI_Model {
    //数据库
    public $errors = array();
    const  dataBase = '';
    public $userId='';
    public $modelename='';
    public $tablename='';


    public function __construct($array=array())
    {



            @$this->userId= $this->session->user_id?$this->session->user_id:0 ;

        // Call the CI_Model constructor
        parent::__construct();
    }
    /**
     * 查询分页数据（使用于简单的单表操作）
     * @param string $model 模型     例如：User_model
     * @param string $table 表名
     * @param string $select_fields 要显示字段
     * @param array $param 查询条件：
     *   compare（比较）:
     *     array($key => $val) $key为要操作的字段，$val为要操作的值
     *     array('name !=' => $name, 'id <' => $id, 'date >' => $date);
     *   like(模糊查询)
     *     array('title' => $match, 'page1' => $match, 'page2' => $match)
     *   customStr（自定义字符串）:
     *     "name='Joe' AND status='boss' OR status='active'"
     *   in:
     *     array('userName' => array('Frank', 'Todd', 'James'))
     * @param string $page 当前页数（查询全部数据时，设置为空）
     * @param string $limit 查询条数（查询全部数据时，设置为空）
     * @param array $order 排序条件：
     *   array($key => $val)
     *   $key为排序依据的字段，
     *   $val为排序的方式【asc (升序，默认)或 desc(降序), 或 random(随机)】
     * @$isReturnCount boole    是否返回总条数
     * @return array|boolean
     *
     */
    public function pageData( $param ="",$select_fields = '', $page = '1', $limit = '10', $order = array(),$isReturnCount = true){
        $model=$this->modelename;
        $table=$this->tablename;
        if(empty($model) || empty($table)){
            return array();
        }
        $this -> load -> model($model);
        $table = $this->db->dbprefix.$table;
        //处理查询字段
        if(!empty($select_fields)){
            $this->db->select($select_fields)->from($table);
        }elseif(isset($this -> $model -> selectFields)){
            $this->db->select($this -> $model -> selectFields)->from($table);
        }else{
            $this->db->select('*')->from($table);
        }
        //处理查询条件
        if (is_array($param) && count($param) > 0){
            $this -> parseParam($param);
        }else{
            if(!empty($param)){
                $this->db->where($param);
            }
        }

        //统计总数
        if($isReturnCount){
            $rs['count']  = $this->db->count_all_results('',false);//不重置查询构造器
            array_push($this -> errors,$this->db->last_query());
        }


        /*  //分页数据处理
          if(isset($page) && isset($param['limit'])){
              //分页边界值 设置
              $offset = $param['page'] <= 1 ? 0 : ($param['page']-1) * $param['limit'];
              $this->db->limit($param['limit'], $offset);
          }*/

        $this->db->limit(  $limit,($page-1)*$limit);

        //排序规则的组合
        if (!empty($order) && is_array($order))
        {
            foreach ($order as $key => $val)
            {
                $this->db->order_by($key, $val);
            }
        }else{
            //默认按照此表的主键倒序
            $primary = $this->getPrimary();
            if(!empty($primary))
            {
                $this->db->order_by($primary, 'DESC');
            }
        }
        $query = $this->db->get();
        array_push($this -> errors,$this->db->last_query());
        $rs['list'] = $query->result_array();
        return $rs;
    }
    /**
     * 解析参数
     */
    private function parseParam($param){
        if(isset($param['compare'])){
            foreach ($param['compare'] as $key => $val){
                if (!empty($val)) $this->db->where($key, $val);
            }
        }
        if(isset($param['like'])){
            foreach ($param['like'] as $key => $val){
                if (!empty($val)) $this->db->like($key, $val);
            }
        }
        if(isset($param['in'])){
            foreach ($param['in'] as $key => $val){
                if (!empty($val)) $this->db->where_in($key, $val);
            }
        }
        if(isset($param['customStr'])){
            if (!empty($val)) $this->db->where($param['customStr']);
        }
    }
    /**
     * 新增信息
     * @param string $table 表名称
     * @param array $param 数据变量
     * @return INT ID
     */
    public function add($table = '', $param = array())
    {

        if(empty($table)){
            $table=$this->tablename;
        }

        if(empty($table) || !is_array($param) || empty ($param)){
            return FALSE;
        }
        //写入数据表
        $this->db->insert($table, $param);
        array_push($this -> errors,$this->db->last_query());
        //返回记录ID
        return $this->db->insert_id();
    }
    /**
     * 更新分类信息
     * @param string  $table   表名称
     * @param string  $primary  表主键
     * @param int    $id     分类ID
     * @param array   $param   更新的数据
     * @return type
     */
    public function update($table = '', $primary = '', $id = 0, $param = array(),$limit=1)
    {
        if(empty($table)){
            $table=$this->tablename;
        }

        if(empty($table) || empty($primary) || empty($param) || empty($id))
        {
            return FALSE;
        }
        $id = (int)$id;
        $this->db->where($primary, $id)
            ->limit($limit)
            ->update($table, $param);
        array_push($this -> errors,$this->db->last_query());
        return $this->db->affected_rows();
    }

    public function Myupdate($row,$key){
        $table=$this->tablename;

        $sql='';
    }



    /**
     * 删除指定ID记录
     * @param string  $table   表名称
     * @param string  $primary  表主键
     * @param array   $id     分类ID
     * @return int
     */
    public function delete($table = '', $primary = '', $id = array()){
        if(empty($table)){
            $table=$this->tablename;
        }
        if(empty($table) || empty($primary) || empty($id)){
            return FALSE;
        }
        $this->db->where_in($primary, $id)
            ->delete($table);
        array_push($this -> errors,$this->db->last_query());
        return $this->db->affected_rows();
    }
    /**
     * 获取表的主键
     * @param string  $database  数据库名称
     * @param strting  $table   表名称
     */
    public function getPrimary($table = '', $database = self::dataBase)
    {
        if(empty($table)){
            $table=$this->tablename;
        }
        if(empty($database) || empty($table))
        {
            return FALSE;
        }
        $sql = "SELECT k.column_name
        FROM information_schema.table_constraints t
        JOIN information_schema.key_column_usage k
        USING (constraint_name,table_schema,table_name)
        WHERE t.constraint_type='PRIMARY KEY'
         AND t.table_schema='qndnew'
         AND t.table_name='qnd_user'";
        $query = $this->db->query($sql)->result_array();
        return isset($query[0]['column_name']) ? $query[0]['column_name'] : false;
    }

    public function  getonebyid($id,$select='*'){
        $table=$this->tablename;
          $result = $this->db->select($select)->from($table)->where("id=".$id)->get()->result_array();
         return $result[0];
    }




    /**
     * debug sql语句
     */
    public function debugSql(){
        if(count($this->errors) > 0){
            foreach($this->errors as $val){
                echo $val.'<br>';
            }
        }
    }


    /**
     * 通过sql语句获取一个查询结果（返回数组格式）
     * @param $sql
     * @param int $isall
     */
    public function GetBySql($sql,$isall=1){
        $query = $this->db->query($sql);
        $result=array();
        if(!$isall){
            $result = $query->row_array();
        }else{
            foreach ($query->result_array() as $key=>$value)
            {
                $result[$key]=$value;
            }
        }
        return $result;
    }






    /**
     *
     * 获取分页查询结果
     * @param $data
     * @return array
     */
  public  function get_server_list($data){
        global $mysql;
        if ($data['limit']!=""){
            if ($data['limit'] != "all"){ $_limit = "  limit ".$data['limit']; }
            // echo str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($data['_select'], $data['_sql'], $data['_order'], $_limit), $data['sql']);exit;
            $list = $this->GetBySql(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($data['_select'], $data['_sql'], $data['_order'], $_limit), $data['sql']));

            $result = array('list' => $list?$list:array(),'total' => count($list),'page' => $data['page'],'epage' => $data['epage'],'total_page' =>1);
            return $result;
        }
        //判断总的条数
        $sql = str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array('count(1) as num', $data['_sql'],'', ''), $data['sql']);

        $newsql=str_replace("group","",$data['sql']);
        if($newsql!=$data['sql']){
            $newsql=str_replace("`group`","",$data['sql']);
            if($newsql==$data['sql']){
                $sql="select count(1)  as num from (".$sql.") as `a`";
            }
        }
        $row =$this->GetBySql($sql,0);
        $total = intval($row['num']);
        //分页返回结果
        $data['page'] = !isset($data['page'])?1:$data['page'];
        $data['epage'] = !isset($data['epage'])?10:$data['epage'];
        $total_page = ceil($total / $data['epage']);
        $_limit = " limit ".($data["epage"] * ($data["page"] - 1)).", {$data['epage']}";
        //echo str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($data['_select'], $data['_sql'], $data['_order'], $_limit), $data['sql']);exit;
        $list = $this->GetBySql(str_replace(array('SELECT', 'SQL', 'ORDER', 'LIMIT'), array($data['_select'], $data['_sql'], $data['_order'], $_limit), $data['sql']));
        $result = array('list' => $list?$list:array(),'total' => $total,'page' => $data['page'],'epage' => $data['epage'],'count' => $total);


        return $result;
    }








}